package com.platform.web.controller.base;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.base.domain.*;
import com.platform.base.service.IBaseLocationService;
import com.platform.base.service.ICollectorTypeService;
import com.platform.common.core.text.Convert;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.netty.NettyUtil;
import com.platform.framework.util.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.platform.common.annotation.Log;
import com.platform.common.enums.BusinessType;
import com.platform.base.service.ICollectorInfoService;
import com.platform.common.core.controller.BaseController;
import com.platform.common.core.domain.AjaxResult;
import com.platform.common.utils.poi.ExcelUtil;
import com.platform.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 采集器信息Controller
 * 
 * @author wangqi
 * @date 2020-09-25
 */
@Controller
@RequestMapping("/base/collector/info")
public class CollectorInfoController extends BaseController
{
    private String prefix = "base/collector/info";

    @Autowired
    private ICollectorInfoService collectorInfoService;

    @Autowired
    private ICollectorTypeService collectorTypeService;

    @Autowired
    private IBaseLocationService baseLocationService;

    @RequiresPermissions("base:collector:info:view")
    @GetMapping(value = { "", "/{typeId}" })
    public String info(@PathVariable(value = "typeId", required = false) String typeId, ModelMap mmap)
    {
        List<CollectorType> types = collectorTypeService.list();
        mmap.put("types", types);
        if(typeId==null){
            typeId = "";
        }
        mmap.put("typeId", typeId);
        mmap.put("location", new BaseLocation());
        return prefix + "/info";
    }

    /**
     * 根据地址查询采集器信息
     * @param locationId
     * @param mmap
     * @return
     */
    @RequiresPermissions("base:collector:info:view")
    @GetMapping("/location/{locationId}")
    public String location(@PathVariable(value = "locationId") String locationId, ModelMap mmap)
    {
        List<CollectorType> types = collectorTypeService.list();
        mmap.put("types", types);
        mmap.put("typeId", "");
        mmap.put("location", baseLocationService.getById(locationId));
        return prefix + "/info";
    }

    /**
     * 查询采集器信息列表
     */
    @RequiresPermissions("base:collector:info:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CollectorInfo collectorInfo)
    {
        startPage();
        List<CollectorInfo> list = collectorInfoService.selectCollectorInfoList(collectorInfo);
        return getDataTable(list);
    }

    /**
     * @Author 王琦
     * @Description //采集器导入
     * @Date 2020/6/19 19:56
     * @Param [file, updateSupport]
     * @return com.platform.common.core.domain.AjaxResult
     */
    @Log(title = "采集器信息导入", businessType = BusinessType.IMPORT)
    @RequiresPermissions("base:collector:info:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<CollectorInfo> util = new ExcelUtil<CollectorInfo>(CollectorInfo.class);
        List<CollectorInfo> infoList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = collectorInfoService.importInfo(infoList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * @Author 王琦
     * @Description //导入模板
     * @Date 2020/6/19 19:56
     * @Param []
     * @return com.platform.common.core.domain.AjaxResult
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<CollectorInfo> util = new ExcelUtil<CollectorInfo>(CollectorInfo.class);
        return util.importTemplateExcel("采集器信息");
    }

    /**
     * 导出采集器信息列表
     */
    @RequiresPermissions("base:collector:info:export")
    @Log(title = "采集器信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CollectorInfo collectorInfo)
    {
        List<CollectorInfo> list = collectorInfoService.selectCollectorInfoList(collectorInfo);
        ExcelUtil<CollectorInfo> util = new ExcelUtil<CollectorInfo>(CollectorInfo.class);
        return util.exportExcel(list, "采集器信息");
    }

    /**
     * 新增采集器信息
     */
    @GetMapping("/add/{locationId}/{typeId}")
    public String add(@PathVariable(value = "locationId") String locationId, @PathVariable(value = "typeId") String typeId,ModelMap mmap)
    {
        List<CollectorType> types = collectorTypeService.list();
        mmap.put("types", types);
        mmap.put("typeId", typeId);
        mmap.put("location", baseLocationService.getById(locationId));
        return prefix + "/add";
    }

    /**
     * 新增保存采集器信息
     */
    @RequiresPermissions("base:collector:info:add")
    @Log(title = "采集器信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CollectorInfo collectorInfo)
    {
        collectorInfo.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(collectorInfoService.insertCollectorInfo(collectorInfo));
    }

    /**
     * 修改采集器信息
     */
    @GetMapping("/edit/{collectorId}")
    public String edit(@PathVariable("collectorId") String collectorId, ModelMap mmap)
    {
        CollectorInfo collectorInfo = collectorInfoService.selectCollectorInfoById(collectorId);
        mmap.put("collectorInfo", collectorInfo);
        List<CollectorType> types = collectorTypeService.list();
        mmap.put("types", types);
        return prefix + "/edit";
    }

    /**
     * 修改保存采集器信息
     */
    @RequiresPermissions("base:collector:info:edit")
    @Log(title = "采集器信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CollectorInfo collectorInfo)
    {
        collectorInfo.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(collectorInfoService.updateCollectorInfo(collectorInfo));
    }



    /**
     * 删除采集器信息
     */
    @RequiresPermissions("base:collector:info:remove")
    @Log(title = "采集器信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(collectorInfoService.deleteCollectorInfoByIds(ids));
    }

    /**
     * 校验采集器信息是否唯一
     */
    @PostMapping("/checkCollectorUnique")
    @ResponseBody
    public String checkCollectorUnique(CollectorInfo collectorInfo)
    {
        return collectorInfoService.checkCollectorUnique(collectorInfo);
    }

    /**
     * 根据地址查询采集器信息
     */
    @PostMapping(value = { "/selectCollectorByLocation/{locationId}", "/selectCollectorByLocation/{collectorId}/{locationId}" })
    @ResponseBody
    public String selectCollectorByLocation(@PathVariable(value = "collectorId", required = false) String collectorId, @PathVariable("locationId") Long locationId)
    {
        CollectorInfo collectorInfo = collectorInfoService.getOne(new QueryWrapper<CollectorInfo>().eq("location_id", locationId));
        if(collectorInfo!=null){
            if(collectorId!=null&&collectorId.equals(collectorInfo.getCollectorId())){
                return "";
            }
            return collectorInfo.getCollectorId();
        }else{
            return "";
        }
    }

    /**
     * 采集器初始化
     */
    @Log(title = "采集器初始化", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:initialize")
    @PostMapping("/initialize/{collectorIds}")
    @ResponseBody
    public AjaxResult initialize(@PathVariable("collectorIds") String collectorIds) throws InterruptedException {
        String message = collectorInfoService.initializeInfo(Convert.toStrArray(collectorIds));
        return AjaxResult.success(message);
    }


    /**
     * 设置采集器心跳时间
     */
    @GetMapping("/heart/{collectorIds}")
    public String heart(@PathVariable("collectorIds") String collectorIds, ModelMap mmap)
    {
        mmap.put("collectorIds",collectorIds);
        return "base/collector/operation/heart";
    }

    /**
     * 设置采集器心跳时间
     */
    @Log(title = "设置采集器心跳时间", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:heart")
    @PostMapping("/heart")
    @ResponseBody
    public AjaxResult heart(CollectorInfo collectorInfo) throws InterruptedException {
        String hex = NettyUtil.get16HexNum(collectorInfo.getHeart());
        if(hex.length()<2){
            hex = "0" + hex;
        }
        String message = collectorInfoService.heartInfo(Convert.toStrArray(collectorInfo.getCollectorIds()), hex);
        return AjaxResult.success(message);
    }

    /**
     * 设置采集器抄表时间
     */
    @GetMapping("/settime/{collectorIds}")
    public String settime(@PathVariable("collectorIds") String collectorIds, ModelMap mmap)
    {
        mmap.put("collectorIds",collectorIds);
        return "base/collector/operation/settime";
    }

    /**
     * 设置采集器抄表时间
     */
    @Log(title = "设置采集器抄表时间", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:settime")
    @PostMapping("/settime")
    @ResponseBody
    public AjaxResult settime(CollectorInfo collectorInfo) throws InterruptedException {
        String hex = NettyUtil.get16HexNum(collectorInfo.getSettime());
        if(hex.length()<2){
            hex = "0" + hex;
        }
        String message = collectorInfoService.settimeInfo(Convert.toStrArray(collectorInfo.getCollectorIds()), hex);
        return AjaxResult.success(message);
    }

    /**
     * 批量设置阀门开度
     */
    @GetMapping("/aperture/{collectorId}")
    public String aperture(@PathVariable("collectorId") String collectorId, ModelMap mmap)
    {
        mmap.put("collectorId",collectorId);
        return "base/collector/operation/aperture";
    }

    /**
     * 批量设置阀门开度
     */
    @Log(title = "批量设置阀门开度", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:aperture")
    @PostMapping("/aperture")
    @ResponseBody
    public AjaxResult aperture(CollectorInfo collectorInfo) throws InterruptedException {
        String hex = NettyUtil.get16HexNum(collectorInfo.getAperture());
        if(hex.length()<2){
            hex = "0" + hex;
        }
        String message = collectorInfoService.apertureInfo(collectorInfo.getCollectorId(), hex);
        return AjaxResult.success(message);
    }

    /**
     * 修改服务器地址
     */
    @GetMapping("/change/{collectorIds}")
    public String change(@PathVariable("collectorIds") String collectorIds, ModelMap mmap)
    {
        mmap.put("collectorIds",collectorIds);
        return "base/collector/operation/change";
    }

    /**
     * 修改服务器地址
     */
    @Log(title = "修改服务器地址", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:change")
    @PostMapping("/change")
    @ResponseBody
    public AjaxResult change(CollectorInfo collectorInfo) throws InterruptedException {
        String serverip = collectorInfo.getIp();
        String[] ips = new String[4];
        String[] ports = new String[4];
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder successMsg = new StringBuilder();
        String n= StringUtils.substringBefore(serverip,".");
        if (Integer.valueOf(n)>255){
            failureNum++;
            failureMsg.append("<br/>" +" 请输入正确的IP地址");
        }else{
        for(int i=0;i<4;i++){
            String s = StringUtils.substringBefore(serverip,".");

            ips[i]= NettyUtil.get16HexNum(Integer.parseInt(s));

            serverip =  StringUtils.substringAfter(serverip, ".");
        }}
        if(failureNum>0){
            failureMsg.insert(0, "很抱歉，采集器设置服务器地址失败！错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        String serverport = NettyUtil.get16HexNum(collectorInfo.getPort());
    /*    if(serverport.length() != 4){
            serverport = String.format("%04d", serverport);
        }*/
        if (serverport.length()==3){
            serverport = "0" + serverport;
        }else if(serverport.length()==2){
            serverport = "00" + serverport;
        }else if (serverport.length()==1){
            serverport = "000" + serverport;
        }else {
            serverport = serverport.substring(serverport.length()-4);
        }
        ports[0] = serverport.substring(0,2);
        ports[1] = serverport.substring(2,4);
        String message = collectorInfoService.changeInfo(Convert.toStrArray(collectorInfo.getCollectorIds()), ips, ports);
        return AjaxResult.success(message);
    }

    /**
     * 查询采集器时间
     */
    @Log(title = "查询采集器时间", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:collect")
    @PostMapping("/collect/{collectorIds}")
    @ResponseBody
    public AjaxResult collect(@PathVariable("collectorIds") String collectorIds) throws InterruptedException {
        String message = collectorInfoService.collectInfo(Convert.toStrArray(collectorIds));
        return AjaxResult.success(message);
    }

    /**
     * 校准采集器时间
     */
    @Log(title = "校准采集器时间", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:correct")
    @PostMapping("/correct/{collectorIds}")
    @ResponseBody
    public AjaxResult correct(@PathVariable("collectorIds") String collectorIds) throws InterruptedException {
        String message = collectorInfoService.correctInfo(Convert.toStrArray(collectorIds));
        return AjaxResult.success(message);
    }

    /**
     * 获取关联设备
     */
    @Log(title = "获取关联设备", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:select")
    @PostMapping("/select/{collectorId}")
    @ResponseBody
    public AjaxResult select(@PathVariable("collectorId") String collectorId) throws InterruptedException {
        String message = collectorInfoService.selectInfo(collectorId);
        return AjaxResult.success(message);
    }

    /**
     * 批量采集数据
     */
    @Log(title = "批量采集数据", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:check")
    @PostMapping("/check/{collectorId}")
    @ResponseBody
    public AjaxResult check(@PathVariable("collectorId") String collectorId) throws InterruptedException {
        String message = collectorInfoService.checkInfo(collectorId);
        return AjaxResult.success(message);
    }

    /**
     * 供暖标志下发
     */
    @Log(title = "供暖标志下发", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:heat")
    @PostMapping("/heat/{collectorIds}")
    @ResponseBody
    public AjaxResult heat(@PathVariable("collectorIds") String collectorIds) throws InterruptedException {
        String message = collectorInfoService.heatInfo(Convert.toStrArray(collectorIds));
        return AjaxResult.success(message);
    }
    /**
     * 非供暖标志下发
     */
    @Log(title = "非供暖标志下发", businessType = BusinessType.OTHER)
    @RequiresPermissions("base:collector:info:heatf")
    @PostMapping("/heatf/{collectorIds}")
    @ResponseBody
    public AjaxResult heatf(@PathVariable("collectorIds") String collectorIds) throws InterruptedException {
        String message = collectorInfoService.heatfInfo(Convert.toStrArray(collectorIds));
        return AjaxResult.success(message);
    }
}
